package com.wing.purchase.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.chanjet.entity.supplier.response.SupplierPartnerClassResponse;
import com.wing.chanjet.feign.ChanjetClient;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.purchase.dao.SupplierCategoryDao;
import com.wing.purchase.model.entity.SupplierCategory;
import com.wing.purchase.model.request.SupplierCategoryForm;
import com.wing.purchase.model.response.SupplierCategoryVO;
import com.wing.sell.model.response.NodeDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 供应商分类-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class SupplierCategoryServiceImpl extends ServiceImpl<SupplierCategoryDao, SupplierCategory> implements SupplierCategoryService {

    private long ROOT_ID=-1l;

    @Autowired
    ChanjetClient chanjetClient;

    @Override
    public int add(SupplierCategoryForm SupplierCategoryForm) {

        //校验

        SupplierCategory SupplierCategory =new SupplierCategory();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(SupplierCategory.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(SupplierCategoryForm, SupplierCategory, copyOptions);

        return baseMapper.insert(SupplierCategory);
    }

    @Override
    public List<SupplierCategoryVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<SupplierCategoryVO> pageList4app(Page page, Map<String, Object> params) {
        List<SupplierCategoryVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public SupplierCategoryVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public int enable(Long id) {
        SupplierCategoryVO SupplierCategoryVO=baseMapper.get4appById(id);
        if (SupplierCategoryVO!=null){
            SupplierCategory SupplierCategory =new SupplierCategory();
            SupplierCategory.setId(id);
            SupplierCategory.setIsDeleted(true);
            int updateCount=baseMapper.updateById(SupplierCategory);
            if (SupplierCategoryVO.getParentId()!=ROOT_ID){
                SupplierCategory SupplierCategory1=new SupplierCategory();
                SupplierCategory1.setId(SupplierCategoryVO.getParentId());
                SupplierCategory1.setHasEnableChild(true);
                baseMapper.updateById(SupplierCategory1);
            }
            return updateCount;
        }
        return 0;
    }

    @Override
    public int disable(Long id) {
        SupplierCategoryVO SupplierCategoryVO=baseMapper.get4appById(id);
        if (SupplierCategoryVO!=null){
            SupplierCategory SupplierCategory =new SupplierCategory();
            SupplierCategory.setId(id);
            SupplierCategory.setIsDeleted(false);
            int updateCount=baseMapper.updateById(SupplierCategory);
            if (SupplierCategoryVO.getParentId()!=ROOT_ID){
                int count=baseMapper.selectCount(new QueryWrapper<SupplierCategory>().eq("parent_id",SupplierCategoryVO.getParentId()).eq("is_deleted",true));
                if (count==0){
                    SupplierCategory SupplierCategory1=new SupplierCategory();
                    SupplierCategory1.setId(SupplierCategoryVO.getParentId());
                    SupplierCategory1.setHasEnableChild(false);
                    baseMapper.updateById(SupplierCategory1);
                }
            }

            return updateCount;
        }
        return 0;
    }

    @Override
    public boolean delete(Long supplierCategoryId) {
        // 查询当前删除分类是否存在子类
        int count = baseMapper.selectCount(new QueryWrapper<SupplierCategory>().eq("parent_id", supplierCategoryId));
        if(count > 0){
            throw new BusinessException(500, "请先删除子分类");
        }
        return removeById(supplierCategoryId);
    }

    @Override
    public JsonResult getTreeData(Long selectId) {
        Map<String, Object> params = new HashMap<>();
        params.put("isDeleted", 1);
        List<SupplierCategoryVO> list=baseMapper.list4app(params);
        Map<Long,List<NodeDataVO>> map=new HashMap<>();

        for (SupplierCategoryVO supplierCategoryVO:list) {
            if (map.containsKey(supplierCategoryVO.getParentId())){
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(supplierCategoryVO.getId().toString());
                nodeDataVO.setName(supplierCategoryVO.getName());
                if(supplierCategoryVO.getIsFinal()!=null){
                    if(!supplierCategoryVO.getIsFinal() || !supplierCategoryVO.getIsDeleted()){
                        nodeDataVO.setDisabled(true);
                    }
                }
                if(selectId != null && selectId.equals(supplierCategoryVO.getId())){
                    nodeDataVO.setSelected(true);
                }
                map.get(supplierCategoryVO.getParentId()).add(nodeDataVO);
            }else{
                List<NodeDataVO> tmpList=new ArrayList<>();
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(supplierCategoryVO.getId().toString());
                nodeDataVO.setName(supplierCategoryVO.getName());
                if(supplierCategoryVO.getIsFinal()!=null ){
                    if(!supplierCategoryVO.getIsFinal() || !supplierCategoryVO.getIsDeleted()) {
                        nodeDataVO.setDisabled(true);
                    }
                }
                if(selectId != null && selectId.equals(supplierCategoryVO.getId())){
                    nodeDataVO.setSelected(true);
                }
                tmpList.add(nodeDataVO);
                map.put(supplierCategoryVO.getParentId(),tmpList);
            }
        }
        List<NodeDataVO> rootList=map.get(-1L);
        if (rootList==null){
            return JsonResult.success();
        }
        constructTree(rootList,map);
        return JsonResult.success(rootList);
    }

    @Override
    public JsonResult syncGetSupplierList() {
        JsonResult<List<SupplierPartnerClassResponse>> supplierList = chanjetClient.getSupplierListPartnerClass();
        List<SupplierPartnerClassResponse> supplierListData = supplierList.getData();
        for (SupplierPartnerClassResponse supplierListDatum : supplierListData) {
            //校验
            SupplierCategory supplierCategory =new SupplierCategory();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(SupplierCategory.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(supplierListDatum, supplierCategory, copyOptions);
            supplierCategory.setName(supplierListDatum.getName());
            supplierCategory.setSupplierNumber(supplierListDatum.getCode());
            supplierCategory.setCjtId(supplierListDatum.getId());
            if(supplierListDatum.getParent()!=null){
                supplierCategory.setCjtParentId(supplierListDatum.getParent().getId());
                LambdaQueryWrapper<SupplierCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(SupplierCategory::getCjtId,supplierListDatum.getParent().getId());
                SupplierCategory supplierCategory1 = baseMapper.selectOne(lambdaQueryWrapper);
                if(supplierCategory1!=null){
                    supplierCategory.setParentId(supplierCategory1.getId());
                }else{
                    supplierCategory.setParentId(-1L);
                }
                supplierCategory.setIsDeleted(true);
            }

            //查询是否存在，不存在则新增，存在则进行修改
            LambdaQueryWrapper<SupplierCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SupplierCategory::getCjtId,supplierCategory.getCjtId());
            List<SupplierCategory> supplierCategories = baseMapper.selectList(lambdaQueryWrapper);
            if(supplierCategories.size()>0){
                for (SupplierCategory category : supplierCategories) {
                    SupplierCategory supplierCategory2 =new SupplierCategory();
                    BeanUtil.copyProperties(category, supplierCategory2, copyOptions);
                    if(category.getParentId()!=null){
                        supplierCategory2.setParentId(-1L);
                    }
                    baseMapper.updateById(supplierCategory2);
                }
            }else{
                baseMapper.insert(supplierCategory);
            }
        }
        return JsonResult.success();
    }

    private void  constructTree(List<NodeDataVO> parentList,Map<Long,List<NodeDataVO>> dataMap){
        for (NodeDataVO node:parentList) {
            Long nodeId=Long.valueOf(node.getValue());
            List<NodeDataVO> childList=dataMap.get(nodeId);
            if (childList!=null){
                node.setChildren(childList);
                constructTree(childList,dataMap);
            }
        }
    }
}
